package com.weatherstation.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Component
public class JwtTokenUtil {

    private static final Logger logger = LoggerFactory.getLogger(JwtTokenUtil.class);

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;

    // 从令牌中获取用户名
    public String getUsernameFromToken(String token) {
        logger.debug("从令牌中获取用户名");
        return getClaimFromToken(token, Claims::getSubject);
    }

    // 从令牌中获取过期时间
    public Date getExpirationDateFromToken(String token) {
        logger.debug("从令牌中获取过期时间");
        return getClaimFromToken(token, Claims::getExpiration);
    }

    // 从令牌中获取指定的声明
    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    // 从令牌中获取所有声明
    private Claims getAllClaimsFromToken(String token) {
        try {
            logger.debug("解析令牌");
            return Jwts.parserBuilder()
                    .setSigningKey(getSigningKey())
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            logger.error("解析令牌失败: {}", e.getMessage());
            throw e;
        }
    }

    // 检查令牌是否已过期
    private Boolean isTokenExpired(String token) {
        try {
            final Date expiration = getExpirationDateFromToken(token);
            boolean isExpired = expiration.before(new Date());
            if (isExpired) {
                logger.warn("令牌已过期，过期时间: {}", expiration);
            } else {
                logger.debug("令牌未过期，过期时间: {}", expiration);
            }
            return isExpired;
        } catch (Exception e) {
            logger.error("检查令牌过期失败: {}", e.getMessage());
            return true;
        }
    }

    // 获取签名密钥
    private Key getSigningKey() {
        byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8);
        return Keys.hmacShaKeyFor(keyBytes);
    }

    // 为用户生成令牌
    public String generateToken(UserDetails userDetails) {
        logger.info("为用户生成令牌: {}", userDetails.getUsername());
        Map<String, Object> claims = new HashMap<>();
        return doGenerateToken(claims, userDetails.getUsername());
    }

    // 生成令牌的具体方法
    private String doGenerateToken(Map<String, Object> claims, String subject) {
        Date issuedAt = new Date(System.currentTimeMillis());
        Date expirationDate = new Date(System.currentTimeMillis() + expiration);
        logger.debug("生成令牌: 用户={}, 发行时间={}, 过期时间={}", subject, issuedAt, expirationDate);
        
        String token = Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(issuedAt)
                .setExpiration(expirationDate)
                .signWith(getSigningKey(), SignatureAlgorithm.HS512)
                .compact();
        
        logger.debug("令牌生成成功");
        return token;
    }

    // 验证令牌
    public Boolean validateToken(String token, UserDetails userDetails) {
        try {
            final String username = getUsernameFromToken(token);
            boolean isValid = (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
            
            if (isValid) {
                logger.debug("令牌验证通过: 用户={}", username);
            } else {
                if (!username.equals(userDetails.getUsername())) {
                    logger.warn("令牌验证失败: 令牌中的用户名({})与UserDetails中的用户名({})不匹配", username, userDetails.getUsername());
                }
                // isTokenExpired已经记录了日志
            }
            
            return isValid;
        } catch (Exception e) {
            logger.error("令牌验证失败: {}", e.getMessage());
            return false;
        }
    }
    
    // 获取令牌剩余有效时间（毫秒）
    public long getTokenRemainingTimeMs(String token) {
        try {
            Date expiration = getExpirationDateFromToken(token);
            long remainingTime = expiration.getTime() - System.currentTimeMillis();
            logger.debug("令牌剩余有效时间: {} ms", remainingTime);
            return remainingTime;
        } catch (Exception e) {
            logger.error("获取令牌剩余时间失败: {}", e.getMessage());
            return 0;
        }
    }
} 